package com.example.pictureview.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.pictureview.widget.ImageLoader;
import com.example.pictureview.widget.MyImageView;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * Created by Administrator on 2017/9/20 0020.
 */

public class ImageAdapter extends PagerAdapter {
    private final String TAG = getClass().getSimpleName();
    private final Deque<View> mCaches = new ArrayDeque<>(3);
    private final List<String> mUrls;
    private final Context mContext;
    private final ImageLoader mImageLoader;

    public ImageAdapter(Context context, ImageLoader imageLoader, List<String> urls) {
        mContext = context;
        mImageLoader = imageLoader;
        mUrls = urls;
    }

    protected void setImageView(ImageView view, int position) {
        final String url = mUrls.get(position);
        mImageLoader.loadImage(view, url);

    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = mCaches.pollFirst();
        if (view == null) {
            view = new MyImageView(mContext);
        }
        container.addView(view);
        setImageView((ImageView) view, position);
        return view;
    }

    @Override
    public int getCount() {
        return mUrls.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
        mCaches.offerLast(view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
